<template>
  <div class="login">
    <Headers :name="flag ? '用户登录' : '用户注册'"></Headers>
    <div class="input">
      <input
        type="text"
        v-model="userName"
        :placeholder="flag ? '请输入您的用户名' : '请填写您的用户名'"
      />
    </div>
    <div class="input">
      <input
        type="password"
        v-model="password"
        :placeholder="flag ? '请输入您的密码' : '请设置您的密码（6-16位）'"
      />
    </div>
    <div class="tip" @click="changeFlag()">
      {{ flag ? '新用户注册' : '已有账号，去登陆' }}
    </div>
    <div class="button flex_center" @click="getBtn">
      {{ flag ? '登录' : '注册' }}
    </div>
  </div>
</template>
<script>
import { login, register } from '@vue/api/login'
import hex_md5 from 'md5'
import { mapState, mapMutations, mapGetters, mapActions } from 'vuex'
export default {
  computed: {
    ...mapState(['userInfo'])
  },
  data() {
    return {
      userName: '', //用户名
      password: '', //密码
      flag: true, // true登录 false注册
    }
  },
  created() {},
  mounted() {
    
  },
  methods: {
    ...mapMutations({
      getUserInfo: 'userInfo',
    }),
    getBtn() {
      //点击按钮校验
      var str = ''
      ;(this.password.length < 6 || this.password.length > 16) &&
        (str = '密码的长度为6-16位')
      this.password === '' && (str = '请输入您的密码')
      this.userName === '' && (str = '请输入您的用户名')
      str ? this.$toast(str, {
        durtaion: 200,
        location: 'center',
      }) : this.flag ? this.login() : this.register()
    },
    login() {
      //登录
      var data = {
        userName: this.userName,
        password: hex_md5(this.password),
      }
      login(data).then((res) => {
        this.$toast(res.data.msg, {
          durtaion: 1000,
          location: 'center',
        })
        this.getUserInfo(res.data.Result) //更新userInfo
        var timer = setTimeout(
          function () {
            clearTimeout(timer)
            this.$router.go(-1)
          }.bind(this),
          996
        )
      }).catch((err) => {
        console.log(err)
      })
    },
    register() {
      //注册
      var data = {
        userName: this.userName,
        password: hex_md5(this.password),
      }
      register(data).then((res) => {
        // console.log(res);
        this.$toast(res.data.msg, {
          durtaion: 200,
          location: 'center',
        })
        this.flag = true
      }).catch((err) => {
        // console.log(err);
      })
    },
    changeFlag() {
      //切换登录和注册
      this.flag = !this.flag
      this.userName = ''
      this.password = ''
    },
  }
}
</script>

<style scoped lang="less">
.login {
  margin-top: 200px;
}
</style>